import re
import sys
import csv
import os

# 正则表达式匹配格式1
pattern1 = re.compile(r'compile method:[^#]*#[^#]*#([^,]+), in jit thread: text size: \d+bytes, compile time: ([\d.]+)ms')
# 正则表达式匹配格式2
pattern2 = re.compile(r'<JSFunction ([^ ]+) \(sfi = [^>]+\)> \(target TURBOFAN\) - took ([\d., ]+) ms')

def parse_file(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()

    functions = {}
    total_compile_time = 0.0

    for line in lines:
        match1 = pattern1.search(line)
        match2 = pattern2.search(line)

        if match1:
            function_name = match1.group(1).strip()
            compile_time = float(match1.group(2).strip())
            functions[function_name] = functions.get(function_name, 0) + compile_time
            total_compile_time += compile_time
        elif match2:
            function_name = match2.group(1).strip()
            compile_times = list(map(float, match2.group(2).strip().split(', ')))
            total_time = sum(compile_times)
            functions[function_name] = functions.get(function_name, 0) + total_time
            total_compile_time += total_time

    return functions, total_compile_time

def main(dir1, dir2, output_csv):
    # 获取两个目录中的文件列表
    files1 = set(os.listdir(dir1))
    files2 = set(os.listdir(dir2))
    common_files = files1 & files2

    # 准备表格数据
    table_data = []

    for file_name in common_files:
        if file_name.endswith('.log'):
            file1_path = os.path.join(dir1, file_name)
            file2_path = os.path.join(dir2, file_name)

            functions1, total_time1 = parse_file(file1_path)
            functions2, total_time2 = parse_file(file2_path)

            # 比较两个文件中函数名完全匹配的函数
            common_functions = set(functions1.keys()) & set(functions2.keys())
            common_compile_time1 = sum(functions1[func] for func in common_functions)
            common_compile_time2 = sum(functions2[func] for func in common_functions)
            common_compile_time_change = (common_compile_time2 - common_compile_time1) / common_compile_time1 * 100 if common_compile_time1 != 0 else float('inf')

            # 添加到表格数据
            table_data.append([
                file_name,
                len(functions1),
                f"{total_time1:.3f}",
                len(functions2),
                f"{total_time2:.3f}",
                len(common_functions),
                f"{common_compile_time1:.3f}",
                f"{common_compile_time2:.3f}",
                f"{common_compile_time_change:.2f}%"
            ])

    # 写入CSV文件
    with open(output_csv, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        headers = [
            "File Name", "v8_func", "v8_time (ms)", "ark_count", "ark_time (ms)",
            "common_count", "v8_common_time (ms)", "ark_common_time (ms)", "change (%)"
        ]
        writer.writerow(headers)
        writer.writerows(table_data)

    print(f"Results written to {output_csv}")

if __name__ == '__main__':
    if len(sys.argv) != 4:
        print("Usage: python compare_compile_times.py <v8_log_path> <ark_log_path> <output_csv>")
        sys.exit(1)

    dir1 = sys.argv[1]
    dir2 = sys.argv[2]
    output_csv = sys.argv[3]
    main(dir1, dir2, output_csv)